// uploadToBOS.js
const sdk = require("@baiducloud/sdk");
const BosClient = sdk.BosClient;
const path = require("path");
const fs = require("fs/promises"); // 使用 fs/promises 替代 fs，以支持 async/await

const config = {
    endpoint: "http://bd.bcebos.com",
    credentials: {
        ak: "6356708ce8d342bf965f2047d7c3cdb2",
        sk: "d4837f696fdf4cf4abf11a80a1067abb",
    },
};

const bucket = "label-anything";
const client = new BosClient(config);

async function uploadFileToBOS(localFilePath, remoteFileName) {
    try {
        const response = await client.putObjectFromFile(
            bucket,
            remoteFileName,
            localFilePath
        );
        console.log(`${remoteFileName} uploaded successfully`);
        return response;
    } catch (error) {
        console.error(`Failed to upload ${remoteFileName}:`, error);
        throw error; // 将错误继续抛出，以便更好的错误处理
    }
}

async function main() {
    const staticDir = path.resolve(__dirname, "dist", "static");
    let uploadedJsFileName, uploadedCssFileName;

    try {
        const files = await fs.readdir(staticDir);
        const jsFiles = files.filter(
            (file) => file.startsWith("index-") && file.endsWith(".js")
        );
        const cssFiles = files.filter(
            (file) => file.startsWith("index-") && file.endsWith(".css")
        );

        for (const jsFile of jsFiles) {
            uploadedJsFileName = jsFile;
            const jsFilePath = path.resolve(staticDir, jsFile);
            await uploadFileToBOS(jsFilePath, `/assets/${jsFile}`);
        }

        for (const cssFile of cssFiles) {
            uploadedCssFileName = cssFile;
            const cssFilePath = path.resolve(staticDir, cssFile);
            await uploadFileToBOS(cssFilePath, `/assets/${cssFile}`);
        }
    } catch (error) {
        if (error.code === "ENOENT") {
            console.error(`Error: The directory ${staticDir} does not exist.`);
        } else {
            console.error("Error reading directory:", error);
        }
        process.exit(1);
    }

    // 判断是否找到对应的js和css文件
    if (!uploadedJsFileName || !uploadedCssFileName) {
        console.error(
            `Not found index-xxx.js or index-xxx.css in dist/static directory!`
        );
        process.exit(1);
    }

    // 处理 index.html 文件
    const distDir = path.resolve(__dirname, "dist");
    const indexPath = path.resolve(distDir, "index.html");
    const indexContent = await fs.readFile(indexPath, "utf-8");
    const CDN_BASE_URL = "https://label-anything.cdn.bcebos.com";

    // 替换 <script> 和 <link> 标签中的地址
    const updatedContent = indexContent
        .replace(
            /<script type="module" crossorigin src="\/static\/index-[a-zA-Z0-9]+.js"><\/script>/,
            `<script type="module" crossorigin src="${CDN_BASE_URL}/assets/${uploadedJsFileName}"></script>`
        )
        .replace(
            /<link rel="stylesheet" href="\/static\/index-[a-zA-Z0-9]+.css">/,
            `<link rel="stylesheet" href="${CDN_BASE_URL}/assets/${uploadedCssFileName}">`
        );

    // 将更新后的内容写回 index.html 文件
    await fs.writeFile(indexPath, updatedContent, "utf-8");
    console.log(`Update index.html successfully!`);
}

// 调用主函数
main();
